package com.qd.system.service.system;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cdqidi.constant.ConstantDto;
import com.cdqidi.db.BaseService;
import com.cdqidi.dto.CacheKey;
import com.cdqidi.excel.ExcelExport;
import com.cdqidi.excel.util.ExportPage;
import com.cdqidi.exception.ApiException;
import com.cdqidi.util.RedisTemplateUtil;
import com.cdqidi.util.SpringContextHolder;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qd.common.sys.domain.entity.system.SystemSetDTO;
import com.qd.common.sys.domain.event.SystemSetEventDTO;
import com.qd.common.sys.event.SystemSetEvent;
import com.qd.system.mapper.SystemSetMapper;
import com.qd.system.model.SystemSet;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;

import static java.util.stream.Collectors.toList;

/**
 * 系统设置
 *
 * @author sjk
 */
@RequiredArgsConstructor
@Service
@Slf4j
public class SystemSetService extends BaseService<SystemSetMapper, SystemSet> {

    private static final String PREFIX_ID = "sys_system_set_code_{0}";

    private final RedisTemplateUtil<SystemSet> redisTemplateUtil;
    private final ObjectMapper objectMapper;
    @Resource
    private HttpServletResponse response;

    /**
     * 保存
     *
     * @param dto 页面对象
     * @return 页面对象
     */
    @Transactional(rollbackFor = Exception.class)
    public SystemSetDTO save(SystemSetDTO dto) {
        final SystemSet model = dtoToModel(dto);
        try {
            if (super.save(model)) {
                TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
                    @Override
                    public void afterCompletion(int status) {
                        if (TransactionSynchronization.STATUS_COMMITTED == status) {
                            log.info("系统设置保存成功，发送SystemSetEvent事件");
                            SpringContextHolder.publishEvent(new SystemSetEvent(new SystemSetEventDTO().setCode(dto.getCode()).setOperator(SystemSetEventDTO.ADD)));
                        }
                    }
                });
                return modelToDto(model);
            }
            throw new ApiException("添加失败");
        } finally {
            clearCache(model);
            model.freeData();
        }
    }

    /**
     * 修改
     *
     * @param dto 页面对象
     * @return 页面对象
     */
    @Transactional(rollbackFor = Exception.class)
    public SystemSetDTO update(SystemSetDTO dto) {
        final SystemSet historyModel = Optional.ofNullable(getById(dto.getCode())).orElseThrow(() -> new ApiException("ID不存在,不能更新"));
        final SystemSet model = dtoToModel(dto);
        try {
            if (super.updateById(model)) {
                return modelToDto(model);
            }
            throw new ApiException("更新失败");
        } finally {
            TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
                @Override
                public void afterCompletion(int status) {
                    if (TransactionSynchronization.STATUS_COMMITTED == status) {
                        log.info("系统设置更新成功，发送SystemSetEvent事件");
                        SpringContextHolder.publishEvent(new SystemSetEvent(new SystemSetEventDTO().setCode(dto.getCode()).setOperator(SystemSetEventDTO.UPDATE)));
                    }
                }
            });
            clearCache(historyModel);
            historyModel.freeData();
            model.freeData();
        }
    }

    /**
     * 批量添加
     *
     * @param mList 数据库对象
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveBatch(List<SystemSet> mList) throws ApiException {
        final List<SystemSetEventDTO> list = mList.stream().map(systemSet -> new SystemSetEventDTO().setCode(systemSet.getCode()).setOperator(SystemSetEventDTO.ADD)).collect(toList());
        try {
            if (!super.saveBatch(mList)) {
                throw new ApiException("批量添加失败");
            }
        } finally {
            TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
                @Override
                public void afterCompletion(int status) {
                    if (TransactionSynchronization.STATUS_COMMITTED == status) {
                        log.info("系统设置批量添加成功，发送SystemSetEvent事件");
                        SpringContextHolder.publishEvent(new SystemSetEvent(list));
                    }
                }
            });
            clearCaches(mList);
        }
    }

    /**
     * 批量更新
     *
     * @param mList 数据库对象
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateBatchIds(List<SystemSet> mList) {
        final List<SystemSetEventDTO> list = mList.stream().map(systemSet -> new SystemSetEventDTO().setCode(systemSet.getCode()).setOperator(SystemSetEventDTO.UPDATE)).collect(toList());
        final List<String> ids = mList.stream().map(SystemSet::getCode).collect(toList());
        final List<SystemSet> historyModelList = checkIds(ids);
        try {
            if (!super.updateBatchById(mList)) {
                throw new ApiException("批量更新失败");
            }
        } finally {
            TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
                @Override
                public void afterCompletion(int status) {
                    if (TransactionSynchronization.STATUS_COMMITTED == status) {
                        log.info("系统设置批量更新成功，发送SystemSetEvent事件");
                        SpringContextHolder.publishEvent(new SystemSetEvent(list));
                    }
                }
            });
            clearCaches(historyModelList);
            historyModelList.clear();
            ids.clear();
        }
    }

    /**
     * 删除，单个
     *
     * @param code 主键
     */
    @Transactional(rollbackFor = Exception.class)
    public void removeById(String code) {
        final SystemSet model = Optional.ofNullable(getById(code)).orElseThrow(() -> new ApiException("数据不存在,不能删除"));
        try {
            if (model.getType() == 0) {
                throw new ApiException("系统内置参数不能删除");
            }
            if (!super.removeById(code)) {
                throw new ApiException("删除失败");
            }
        } finally {
            TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
                @Override
                public void afterCompletion(int status) {
                    if (TransactionSynchronization.STATUS_COMMITTED == status) {
                        log.info("系统设置删除成功，发送SystemSetEvent事件");
                        SpringContextHolder.publishEvent(new SystemSetEvent(new SystemSetEventDTO().setCode(code).setOperator(SystemSetEventDTO.DELETE)));
                    }
                }
            });
            clearCache(model);
            model.freeData();
        }
    }

    /**
     * 批量删除
     *
     * @param ids 主键集合
     */
    @Transactional(rollbackFor = Exception.class)
    public void removeBatchIds(List<String> ids) {
        List<SystemSet> historyModelList = checkIds(ids);
        final List<SystemSetEventDTO> list = ids.stream().map(code -> new SystemSetEventDTO().setCode(code).setOperator(SystemSetEventDTO.DELETE)).collect(toList());
        try {
            historyModelList.forEach(systemSet -> {
                if (systemSet.getType() == 0) {
                    throw new ApiException("系统内置参数不能删除");
                }
            });
            if (!super.removeByIds(ids)) {
                throw new ApiException("批量删除失败");
            }
        } finally {
            TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
                @Override
                public void afterCompletion(int status) {
                    if (TransactionSynchronization.STATUS_COMMITTED == status) {
                        log.info("系统设置批量删除成功，发送SystemSetEvent事件");
                        SpringContextHolder.publishEvent(new SystemSetEvent(list));
                    }
                }
            });
            clearCaches(historyModelList);
            historyModelList.clear();
        }
    }

    /**
     * 根据传入对象构建查询参数，判断是否存在
     *
     * @param dto 参数
     * @return 存在为true
     */
    @Transactional(readOnly = true)
    public Boolean isExists(SystemSetDTO dto) {
        final QueryWrapper<SystemSet> queryWrapper = createQueryWrapper(dto);
        final boolean exists = super.count(queryWrapper) > 0;
        queryWrapper.clear();
        return exists;
    }

    /**
     * 根据主键判断数据是否存在
     *
     * @param code 主键
     * @return 存在为true
     */
    @Transactional(readOnly = true)
    public Boolean isExistsById(String code) {
        boolean exists = false;
        if (StringUtils.hasLength(code)) {
            final SystemSet model = getById(code);
            exists = (null != model);
            if (exists) {
                model.freeData();
            }
        }
        return exists;
    }

    /**
     * 根据主键获取数据
     *
     * @param code 主键
     * @return 单条记录
     */
    public SystemSet getById(String code) {
        final String key = RedisTemplateUtil.getRedisCacheKey(PREFIX_ID, code);
        return redisTemplateUtil.get(new CacheKey().setKey(key).setTimeout(ConstantDto.REDIS_TIME_OUT_DAY), () -> super.getById(code), SystemSet.class);
    }

    /**
     * 根据主键获取数据
     *
     * @param code 主键
     * @return 单条记录，转换成页面对象
     */
    @Transactional(readOnly = true)
    public SystemSetDTO getByIdDto(String code) {
        return Optional.ofNullable(getById(code)).map(this::modelToDto).orElse(null);
    }

    /**
     * 根据条件查询单条数据
     *
     * @param dto 查询参数
     * @return 单条记录
     */
    public SystemSet getOne(SystemSetDTO dto) {
        final QueryWrapper<SystemSet> queryWrapper = createQueryWrapper(dto);
        SystemSet model = super.getOne(queryWrapper);
        queryWrapper.clear();
        return model;
    }

    /**
     * 根据条件查询单条数据
     *
     * @param dto 查询参数
     * @return 单条记录，转换成页面对象
     */
    @Transactional(readOnly = true)
    public SystemSetDTO getOneDto(SystemSetDTO dto) {
        return Optional.ofNullable(getOne(dto)).map(this::modelToDto).orElse(null);
    }

    /**
     * 根据条件查询列表数据
     *
     * @param dto 查询参数
     * @return 列表数据
     */
    public List<SystemSet> getList(SystemSetDTO dto) {
        final QueryWrapper<SystemSet> queryWrapper = createQueryWrapper(dto);
        final List<SystemSet> list = super.list(queryWrapper);
        queryWrapper.clear();
        return list;
    }

    /**
     * 根据条件查询列表数据
     *
     * @param dto 查询参数
     * @return 列表数据，转换成页面对象
     */
    @Transactional(readOnly = true)
    public List<SystemSetDTO> getListDto(SystemSetDTO dto) {
        return modelToDtoList(getList(dto));
    }

    /**
     * 分页数据
     *
     * @param page 分页对象
     * @param dto  查询参数
     * @return 分页信息
     */
    @Transactional(readOnly = true)
    public IPage<SystemSetDTO> page(Page<SystemSet> page, SystemSetDTO dto) {
        final QueryWrapper<SystemSet> queryWrapper = createQueryWrapper(dto, "sys.");
        final IPage<SystemSetDTO> iPage = baseMapper.page(page, queryWrapper);
        Optional.ofNullable(iPage.getRecords()).ifPresent(l -> l.forEach(this::buildDisplay));
        queryWrapper.clear();
        return iPage;
    }

    /**
     * 导出Excel
     *
     * @param query 查询条件
     */
    @Transactional(readOnly = true)
    public void export(SystemSetDTO query) {
        final ExportPage<SystemSet, SystemSetDTO> exportPage = new ExportPage<>();
        try {
            final List<SystemSetDTO> list = exportPage.getAllForPage(page -> page(page, query).getRecords());
            try {
                ExcelExport.downloadExcel(response, SystemSetDTO.class, () -> list);
            } catch (IOException e) {
                log.error("导出失败", e);
                throw new ApiException("导出失败");
            }
        } finally {
            exportPage.freeData();
        }
    }


    /**
     * 清空缓存
     *
     * @param model 数据库对象
     */
    public void clearCache(SystemSet model) {
        if (null == model) {
            return;
        }
        redisTemplateUtil.deleteByKey(RedisTemplateUtil.getRedisCacheKey(PREFIX_ID, model.getCode()));
    }

    /**
     * 批量清空缓存
     *
     * @param list 数据库对象
     */
    public void clearCaches(List<SystemSet> list) {
        if (null == list || list.isEmpty()) {
            return;
        }
        List<String> ids = list.stream().map(model -> RedisTemplateUtil.getRedisCacheKey(PREFIX_ID, model.getCode())).collect(toList());
        if (!ids.isEmpty()) {
            redisTemplateUtil.deleteByKey(ids);
            ids.clear();
        }
    }

    /**
     * 数据库对象转页面对象
     *
     * @param model 数据库对象
     * @return 页面对象
     */
    @SneakyThrows
    public SystemSetDTO modelToDto(SystemSet model) {
        if (null == model) {
            return null;
        }
        final SystemSetDTO dto = new SystemSetDTO();
        dto.setCode(model.getCode());
        dto.setName(model.getName());
        dto.setValue(objectMapper.readTree(model.getValue()));
        dto.setType(model.getType());
        dto.setNote(model.getNote());
        dto.setAddTime(model.getAddTime());
        dto.setUpdateTime(model.getUpdateTime());
        buildDisplay(dto);
        return dto;
    }

    /**
     * 页面对象转数据库对象
     *
     * @param dto 页面对象
     * @return 数据库对象
     */
    public SystemSet dtoToModel(SystemSetDTO dto) {
        if (null == dto) {
            return null;
        }
        final SystemSet model = new SystemSet();
        model.setCode(dto.getCode());
        model.setName(dto.getName());
        model.setValue(dto.getValue().toString());
        model.setType(dto.getType());
        model.setNote(dto.getNote());
        model.setAddTime(dto.getAddTime());
        model.setUpdateTime(dto.getUpdateTime());
        return model;
    }

    /**
     * 码表转换
     *
     * @param dto 页面对象
     */
    public void buildDisplay(SystemSetDTO dto) {
        Optional.ofNullable(dto.getType()).ifPresent(type -> {
            if (type == 0) {
                dto.setTypeDisplay("是");
            } else {
                dto.setTypeDisplay("否");
            }
        });
        dto.setValueDisplay(dto.getValue().toString());
    }

    /**
     * 数据库对象转页面对象
     *
     * @param list 数据库对象
     * @return 页面对象
     */
    public List<SystemSetDTO> modelToDtoList(List<SystemSet> list) {
        return Optional.ofNullable(list).orElse(Collections.emptyList()).stream().map(this::modelToDto).collect(toList());
    }

    /**
     * 页面对象转数据库对象
     *
     * @param list 页面对象
     * @return 数据库对象
     */
    public List<SystemSet> dtoToModelList(List<SystemSetDTO> list) {
        return Optional.ofNullable(list).orElse(Collections.emptyList()).stream().map(this::dtoToModel).collect(toList());
    }

    /**
     * 拼装查询参数，除了主键的其他字段会自动加入进来
     *
     * @param dto 查询参数，不为空的属性会被自动加入
     */
    public QueryWrapper<SystemSet> createQueryWrapper(SystemSetDTO dto) {
        return createQueryWrapper(dto, "");
    }

    /**
     * 拼装查询参数，除了主键的其他字段会自动加入进来
     *
     * @param dto        查询参数，不为空的属性会被自动加入
     * @param tableAlias 表别名
     */
    public QueryWrapper<SystemSet> createQueryWrapper(SystemSetDTO dto, String tableAlias) {
        final QueryWrapper<SystemSet> queryWrapper = new QueryWrapper<>();
        if (null != dto) {
            if (StringUtils.hasLength(tableAlias) && tableAlias.charAt(tableAlias.length() - 1) != '.') {
                tableAlias += ".";
            }
            if (StringUtils.hasLength(dto.getCode())) {
                queryWrapper.like(tableAlias + "code", dto.getCode());
            }
            if (StringUtils.hasLength(dto.getName())) {
                queryWrapper.like(tableAlias + "name", dto.getName());
            }
        }
        return queryWrapper;
    }

    /**
     * 批量检查主键在数据库中是否存在
     *
     * @param ids 主键集合
     * @return 主键查询出来的集合
     */
    public List<SystemSet> checkIds(List<String> ids) {
        if (null == ids || ids.isEmpty()) {
            throw new ApiException("ids不能为空");
        }
        final List<SystemSet> list = super.listByIds(ids);
        if (list.isEmpty()) {
            throw new ApiException("ids不存在" + Arrays.toString(ids.toArray()));
        }
        if (ids.size() == list.size()) {
            return list;
        }
        List<String> dbIds = list.stream().map(SystemSet::getCode).collect(toList());
        final List<String> notExistsList = ids.stream().filter(id -> !dbIds.contains(id)).collect(toList());
        dbIds.clear();
        if (!notExistsList.isEmpty()) {
            throw new ApiException("ids不存在" + Arrays.toString(notExistsList.toArray()));
        }
        return list;
    }
}